package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import domain.Concept;
import domain.QA;
import domain.Stock;
import domain.StockVo;
import login.SimulationLogin;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private final static String IMG_URL_PREFIX = "data:image/png;base64,";

    public static <T> T parse(String json,TypeReference<T> tr){
        T data = JSON.parseObject(json, tr);
        return data;
    }

    public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
        @SuppressWarnings("unchecked")
        List<T> ts = (List<T>) JSONArray.parseArray(jsonString, clazz);
        return ts;
    }

    public static List<StockVo> convertToStockVos(String json){
        List<Stock> imageList = null;
        TypeReference<List<Stock>> imageTypeList = new TypeReference<List<Stock>>(){};
        TypeReference<List<QA>> qaTypeList = new TypeReference<List<QA>>(){};
        JSONObject jsonObject1 = JSON.parseObject(json);
        JSONObject jsonObjectTemp = JSON.parseObject(jsonObject1.getString("data"));
        JSONObject jsonObjectResult = new JSONObject();

        List<Stock> stockList = parse(JSON.toJSONString(jsonObjectTemp.get("stocks")),imageTypeList);
        //对imgurl进行拼接，并请求img码，然后再拼接成可访问的url
        List<StockVo> stockVoList = listToStockVoList(stockList);
        return stockVoList;
    }

    public static String convertToConcept(String json){
        List<Stock> imageList = null;
        TypeReference<List<Stock>> imageTypeList = new TypeReference<List<Stock>>(){};
        TypeReference<List<QA>> qaTypeList = new TypeReference<List<QA>>(){};
        JSONObject jsonObject1 = JSON.parseObject(json);
        JSONObject jsonObjectTemp = JSON.parseObject(jsonObject1.getString("data"));
        JSONObject jsonObjectResult = new JSONObject();
        //过滤无用的属性，只保留这四个
        jsonObjectResult.put("name",jsonObjectTemp.get("name"));
        jsonObjectResult.put("desc",jsonObjectTemp.get("desc"));
        List<QA> qaList = parse(JSON.toJSONString(jsonObjectTemp.get("question_answers")),qaTypeList);
        if (CollectionUtils.isNotEmpty(qaList)){
            List<QA> qas = convertQA(qaList);
            //正则匹配只获取<p>或<img>中的属性
            jsonObjectResult.put("question_answers",qas);
        }else{
            jsonObjectResult.put("question_answers",null);
        }

        return JSON.toJSONString(jsonObjectResult);
    }

    public static List<QA> convertQA(List<QA> qaList){
        List<QA> qas = new ArrayList<QA>();
        if (CollectionUtils.isNotEmpty(qaList)){
            for (QA qa : qaList){
                String as = qa.getHtmlAnswer();
                QA qaTemp = new QA();
                qaTemp.setQuestion(qa.getQuestion());
                if (as.indexOf("img") == -1){
                    //是文字
                    String regex="<p.*?>(.*?)</p>";
                    Pattern p =Pattern.compile(regex);
                    Matcher m=p.matcher(as);
                    if(m.find()){
                        qaTemp.setHtmlAnswer(m.group(1));
                    }
                }else{
                    //是图片
                    String regex="src\\s*=\\s*\"?(.*?)(\"|>|\\s+)";
                    Pattern p =Pattern.compile(regex);
                    Matcher m=p.matcher(as);
                    if(m.find()){
                        qaTemp.setHtmlAnswer(m.group(1));
                    }
                }
                qas.add(qaTemp);
            }
        }
        return qas;
    }


    public static List<StockVo> listToStockVoList(List<Stock> stockList){
        //创建默认客户端
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        List<StockVo> stockVos = new ArrayList<StockVo>();
        try {
            for (Stock stock : stockList) {
                StockVo stockVo = new StockVo();
                stockVo.setStockCode(symbolToStockcode(stock.getSymbol()));
                String descUrl = stock.getDesc_url();
                if (StringUtils.isNotEmpty(descUrl)) {
                    //创建
                    HttpGet httpGet = new HttpGet(descUrl + "&cat=n2");
                    CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
                    String result = "";
                    //如果模拟登录成功
                    if(httpResponse.getStatusLine().getStatusCode() == 200) {
                        String jsonString = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
                        JSONObject jsonObjectTemp = JSON.parseObject(jsonString);
                        String ImgStr = jsonObjectTemp.getString("ImgStr");
                        String ImgUrl = IMG_URL_PREFIX + ImgStr;
                        stockVo.setDesc_url_real(ImgUrl);
                    }

                    httpGet.abort();
                }
                logger.info("stockCode:{},url:{}",stockVo.getStockCode(),stockVo.getDesc_url_real());
                stockVos.add(stockVo);
            }


        } catch(UnsupportedEncodingException e){
            e.printStackTrace();
        } catch(ClientProtocolException e){
            e.printStackTrace();
        } catch(IOException e){
            e.printStackTrace();
        }
        return stockVos;
    }

    public static String symbolToStockcode(String symbol){
        String[] strArray = null;
        strArray = symbol.split("\\.");
        String stockCode = strArray[1]+strArray[0];
        return stockCode;
    }

    public static void convertConceptId(String json,Set<Long> set){
        TypeReference<List<Concept>> conceptList = new TypeReference<List<Concept>>(){};
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject jsonObjectTemp = JSON.parseObject(jsonObject.getString("data"));
        JSONArray arr=jsonObjectTemp.getJSONArray("items");
        System.out.println(arr);
        if(arr != null){
            for (int i = 0;i < arr.size();i++){
                String concept = arr.getString(i);
                //处理这个[17363998,"民航",1,1,35.93]，获取id
                String[] str = concept.split(",");
                String conceptIdStr = str[0].substring(1);
                Long conceptId = Long.parseLong(conceptIdStr);
                if (!set.contains(conceptId)){
                    set.add(conceptId);
                }
            }
        }
    }
}
